package com.github.cyf.config.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;

/**
 * MySQL 数据源配置
 * @author chenyifan
 * @create 2024-03-12 21:36
 */
@Configuration
@MapperScan(basePackages = {"com.github.cyf.mapper.db1"},
        sqlSessionFactoryRef = "db1SqlSessionFactory",
        sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DB1DataSourceConfigure {

    private final DataSource dataSource;

    public DB1DataSourceConfigure(@Qualifier("db1DataSource") DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(org.apache.ibatis.session.Configuration configuration) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfiguration(configuration);
        // 设置该包下所有的类型都拥有默认的别名，即类名且不区分大小写
        bean.setTypeAliasesPackage("com.github.cyf.domain.po");
        // 设置 mapper.xml 位置
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = pathMatchingResourcePatternResolver.getResources("classpath:mapper/db1/*Mapper.xml");
        bean.setMapperLocations(resources);
        return bean.getObject();
    }

    @Bean("db1SqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
